//
//  WXActivityApplyViewController.m
//  CarJX
//
//  Created by xcq on 14-9-26.
//  Copyright (c) 2014年 KK. All rights reserved.
//

#import "WXActivityApplyViewController.h"
#import "WXChangeCarTyeViewController.h"
#import "CLUIBaseNavigationController.h"
#import "WXFormat.h"
 #define Point @".0123456789\n"
#define TOP_POINT [NSValue valueWithCGPoint:CGPointMake([UIScreen mainScreen].bounds.size.width / 2, ([UIScreen mainScreen].bounds.size.height  / 2.6) )]


@interface WXActivityApplyViewController ()<UITextViewDelegate>{
    UITextField *tempField;
    CGRect fremeRect;
}

@end

@implementation WXActivityApplyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) viewWillAppear:(BOOL)animated{
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) viewDidDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0) {
        self.noteLabel.hidden = NO;
    }else{
        self.noteLabel.hidden = YES;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:@"活动报名"];
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:nil andCustom:NO];

     self.remark.layer.cornerRadius = 10.0f;
     fremeRect = self.view.frame;
    _activityId = self.dicinfo[@"ID"];
    _priceText.placeholder = [NSString stringWithFormat:@"最低价格%@元",self.dicinfo[@"MIN_PRICE"]];
}
- (IBAction)confirmationActivity:(id)sender {
    [self.view endEditing:YES];
    if (!_pro) {
        _pro = [[Product alloc] init];
    }
    if (_contactText.text.length == 0) {
        
            [self.view makeToast:@"联系人不能为空" duration:2.0f position:TOP_POINT];

        
    }else if (_peopleNum.text.length == 0){
        
        [self.view makeToast:@"报名人数不能为空" duration:2.0f position:TOP_POINT];
        
        
    }else if (_phoneText.text.length == 0){
        
            [self.view makeToast:@"电话号码不能为空" duration:2.0f position:TOP_POINT];

        
    }else if (_carNumText.text.length == 0){
        
           [self.view makeToast:@"车牌号不能为空" duration:2.0f position:TOP_POINT];
            
        
    }else if(_priceText.text.length == 0){
        
        [self.view makeToast:@"价格不能为空" duration:2.0f position:TOP_POINT];
    
        
    }else if ([_priceText.text intValue] < [self.dicinfo[@"MIN_PRICE"] intValue]) {
        [self.view makeToast:@"不能低于最低价格" duration:2.0f position:TOP_POINT];
    }
    else if(_contactText.text.length > 0 && ![WXFormat validateNickname:_contactText.text]) {
        
        [self.view makeToast:@"输入正确的名字" duration:2.0f position:TOP_POINT]  ;
        
    }else{
        
        if ([WXFormat validateCarNo:_carNumText.text]) {
            
            [self.view makeToast:@"请输入正确的车牌号" duration:2.0f position:TOP_POINT];
            return;
        }
        
        
        NSString *carNum = [_changeRegion.titleLabel.text stringByAppendingString:_carNumText.text];
        
        if (!self.dataSource) {
            self.dataSource = [CurrentDataSource dataSourceWithRequestor:self];
        }
        self.dataSource.info = @{@"activeid" : _activityId
                                 , @"memberid" : [Common currentUserId]
                                 ,@"money" : _priceText.text
                                 , @"name" : _contactText.text
                                 , @"point": @"0"
                                 , @"pay_price" : _priceText.text
                                 , @"phone" : _phoneText.text
                                 , @"car_num" : carNum,@"num" : _peopleNum.text
                                 , @"remark" : self.remark.text};
        
        [self.dataSource activitysSignUp:^(id result) {
            _pro.orderId = [result customObjectForkey:@"order"];
            _pro.subject = @"活动";
            _pro.body = @"报名";
            _pro.price = [_priceText.text floatValue];
            [self CreateOrderInfo:_pro
                          tradeNo:[result customObjectForkey:@"order"]
                         callback:^(NSDictionary *resultDic) {
                if ( [[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"])
                {
                    [self.navigationController.view makeToast:@"付款成功" duration:1.5f position:TOP_POINT];
                    [self performSelector:@selector(backTo) withObject:nil afterDelay:1.5f];
                }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"4000"])
                {
                                    [self.view makeToast:@"订单支付失败" duration:2.0f position:TOP_POINT];
                    
                }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"]){
                                    [self.view makeToast:@"您中途取消了支付" duration:2.0f position:TOP_POINT];
                    
                }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6002"])
                {
                    
                    [self.view makeToast:@"网络不通畅,请重试" duration:2.0f position:TOP_POINT];
                    
                }
            }];
            
        } andFail:^(id result) {
        
        }];
     
    }
    
}

 
- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0.5f animations:^{
        [self.view setFrame:fremeRect];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - textField 代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    return YES;
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField;
{
//    NSDictionary *userInfo = [notification userInfo];
//    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    if (self.view.frame.origin.y < 0) {
        return;
    }
    [UIView animateWithDuration:0.5f animations:^{
        CGRect rect = self.view.frame;
        rect.origin.y -= 160;
        self.view.frame = rect;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (textField.tag == 225 && [toBeString length] >= 7) { //如果输入框内容大于20则弹出警告
            textField.text = [toBeString substringToIndex:7];
          
            return NO;
    }
    if (textField.tag == 222 && [toBeString length] >= 10) {
        
        textField.text = [toBeString  substringToIndex:10];
 
        return NO;
    }
    if (textField.tag == 223 && [toBeString length] >= 11) {
        
        textField.text = [toBeString substringToIndex:11];
        return NO;
        
    }
    if (textField.tag == 223) {
        NSCharacterSet *cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:Point]invertedSet];
        
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
        BOOL canChange = [string isEqualToString:filtered];
        return canChange;
    }
    if (textField.tag == 224 && [toBeString length] >= 6) {
        textField.text = [toBeString substringToIndex:6];
        return NO;
    }
    if (textField.tag == 230 && [toBeString length] >= 4) {
        textField.text = [toBeString substringToIndex:4];
        return NO;
    }
    if (textField.tag == 225) {
        NSCharacterSet *cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:Point]invertedSet];
        
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
        
        BOOL canChange = [string isEqualToString:filtered];
        
        return canChange;
    }
     return YES;
}




- (IBAction)priceChangeA:(id)sender {

    
    UITextField *text = (UITextField *)sender;
    
    NSString *strText = text.text;
    
    if ([[strText componentsSeparatedByString:@"."] count] > 0) {
 
    }else{
    
        text.text = [strText stringByAppendingString:@".0"];
    }
}

- (IBAction)changeProvinces:(id)sender {
    [self.view endEditing:YES];
    WXChangeCarTyeViewController *change = [[WXChangeCarTyeViewController alloc] init];
    change.callBack = ^(NSString *seleteKey){
        [_changeRegion setTitle:seleteKey forState:UIControlStateNormal];
    };
  //  [self.navigationController pushViewController:change animated:YES];
    CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:change ];
    
    [self presentViewController:base animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
